import React, { Component } from 'react';
import PropTypes from 'prop-types'
import {Upload, Icon, Modal, message} from 'antd';
import { apiUrl } from '../../api/constant'

/*var token = ;
if (token) {
    token = window.atob(token);
}*/
export default class PhotoUpload extends Component {
    static propTypes = {
        fileList: PropTypes.array,
        limit: PropTypes.number,
        fileSize: PropTypes.number.isRequired,
        data: PropTypes.object,
        errMessage: PropTypes.string,
        upload: PropTypes.func
    };

    static defaultProps = {
        fileList: [],
        limit: 5,
        actionUrl: `${apiUrl}/image/upload/`
    };

    constructor(props) {
        super(props);

        this.state = {
            previewVisible: false,
            previewImage: '',
            fileList: this.props.fileList || []
        };
        this.handleBeforeUpload = this.handleBeforeUpload.bind(this);
    }

    handleCancel = () => this.setState({previewVisible: false})

    handlePreview = (file) => {
        this.setState({
            previewImage: file.url || file.thumbUrl,
            previewVisible: true,
        });
    }

    handleChange = ({file, fileList}) => {
        const {limit, errMessage} = this.props
        let url2
        fileList = fileList.slice(0 - limit)
        fileList = fileList.filter((file) => {
            if (file.response) {
                try {
                    if (file.response.status === 200) {
                        message.success('图片上传成功')
                        file.response.data.forEach(item => {
                            if(item.size === '640X640') {
                                file.imageKey1 = item.id
                                file.url = item.url
                            } else if (item.size === '640X450') {
                                file.imageKey2 = item.id
                                url2 = item.url
                            }
                        })
                    }
                } catch (err) {
                    message.error(errMessage)
                    return false
                }
            }
            return true
        })
        this.setState({
            fileList: fileList
        })
        if (this.props.callBack && 'done' === file.status) {
            this.props.callBack(fileList,url2);
        }

    }

    handleBeforeUpload(file) {
        let {fileSize, fileType} = this.props;
        /*let reader = new FileReader();
        let image = new Image();
        reader.readAsDataURL(file);
        reader.onload = () => {
            image.src = reader.result;
            image.onload = () => {
                console.log(image.height, image.width);
            }
        }*/
        fileType = fileType || ['image/jpg','image/jpeg', 'image/png']
        const isExt = fileType.filter(item => {
                return item === file.type
            }).length > 0;

        if (!isExt) {
            message.error('请上传正确的格式图片!');
            return false;
        }
        let flag = file.size > fileSize
        if (flag) {
            message.error(`${file.name}大小超过限制`)
            return !flag;
        }
        return true
    }

    componentWillReceiveProps(nextProps) {
        if (this.props.fileList !== nextProps.fileList) {
            this.setState({
                fileList: nextProps.fileList
            })
        }
    }

    handlePhotoRemove = () => {
        const {onRemove} = this.props;
        let flag = false;
        Modal.confirm({
            title: '确认删除该商品图片？',
            onOk() {
                if(onRemove) {
                    onRemove();
                }
                flag = true
            },
            onCancel() { flag = false },
        })
        return flag;
    }

    render() {
        const {previewVisible, previewImage} = this.state;
        let {actionUrl, data, limit, showRemoveIcon, buttonText} = this.props;
        const uploadButton = (
            <div>
                <Icon type="plus"/>
                <div className="ant-upload-text">{buttonText || '上传'}</div>
            </div>
        );
        return (
            <div className="clearfix">
                {showRemoveIcon}
                <Upload
                    action={ actionUrl }
                    listType="picture-card"
                    fileList={this.state.fileList}
                    multiple={true}
                    data={data}
                    headers={{'X-Requested-With': null, "accept": "application/json"}}
                    beforeUpload={ this.handleBeforeUpload }
                    onPreview={this.handlePreview}
                    onChange={this.handleChange}
                    showUploadList={{
                        showRemoveIcon: showRemoveIcon === false ? false : true
                    }}
                    onRemove={this.handlePhotoRemove}
                >
                    {this.state.fileList.length >= limit ? null : uploadButton}
                </Upload>
                <Modal visible={previewVisible}
                       footer={null}
                       onCancel={this.handleCancel}>
                    <img alt="example"
                         style={{width: '100%'}}
                         src={previewImage}/>
                </Modal>
            </div>
        );
    }
}

